print("open computer")
local properties, system
system = {
    fileName = "s_dat", 
    file = nil,      
}
system.init = function()
    system.file = io.open(system.fileName, "r")
    if system.file then
        local tmpProp = textutils.unserialise(system.file:read("a"))
        properties = system.reset()
        for k, v in pairs(properties) do
            if tmpProp[k] then
                properties[k] = tmpProp[k]
            end
        end
        system.file:close()
    else
        properties = system.reset()
        system.updatePersistentData()
    end
end

system.reset = function()
    return {
    offset = 1,
    length = 20.0,
    INPUT = "top",
    Face = "west"
    }
end

system.updatePersistentData = function()
    system.write(system.fileName, properties)
end

system.write = function(file, obj)
    system.file = io.open(file, "w")
    system.file:write(textutils.serialise(obj))
    system.file:close()
end

system.init()

commands.execAsync(string.format(
"/gamerule commandBlockOutput false"
))

local vector = {}
local newVec = function(x, y, z)
    if type(x) == "table" then
        return setmetatable({x = x.x, y = x.y, z = x.z}, {__index = vector})
    elseif x and y and z then
        return setmetatable({x = x, y = y, z = z}, {__index = vector})
    else
        return setmetatable({x = 0, y = 0, z = 0}, {__index = vector})
    end
end

function vector:zero()
    self.x = 0
    self.y = 0
    self.z = 0
    return self
end

function vector:copy()
    return newVec(self.x, self.y, self.z)
end

local square = function(num)
    return num * num
end

function vector:len()
    return math.sqrt(square(self.x) + square(self.y) + square(self.z))
end

function vector:norm()
    local l = self:len()
    if l == 0 then
        self:zero()
    else
        self.x = self.x / l
        self.y = self.y / l
        self.z = self.z / l
    end
    return self
end

function vector:nega()
    self.x = -self.x
    self.y = -self.y
    self.z = -self.z
    return self
end

function vector:add(v)
    self.x = self.x + v.x
    self.y = self.y + v.y
    self.z = self.z + v.z
    return self
end

function vector:sub(v)
    self.x = self.x - v.x
    self.y = self.y - v.y
    self.z = self.z - v.z
    return self
end

function vector:scale(num)
    self.x = self.x * num
    self.y = self.y * num
    self.z = self.z * num
    return self
end

function vector:unpack()
    return self.x, self.y, self.z
end

local quat = {}
function quat.vecRot(q, v)
    local x = q.x * 2
    local y = q.y * 2
    local z = q.z * 2
    local xx = q.x * x
    local yy = q.y * y
    local zz = q.z * z
    local xy = q.x * y
    local xz = q.x * z
    local yz = q.y * z
    local wx = q.w * x
    local wy = q.w * y
    local wz = q.w * z
    local res = {}
    res.x = (1.0 - (yy + zz)) * v.x + (xy - wz) * v.y + (xz + wy) * v.z
    res.y = (xy + wz) * v.x + (1.0 - (xx + zz)) * v.y + (yz - wx) * v.z
    res.z = (xz - wy) * v.x + (yz + wx) * v.y + (1.0 - (xx + yy)) * v.z
    return newVec(res.x, res.y, res.z)
end

local faces = {
    up = newVec(0, 1, 0)}
local FACE ={
    north = newVec(0, 0, -1),
    south = newVec(0, 0, 1),
    west = newVec(-1, 0, 0),
    east = newVec(1, 0, 0)
}

local block_offset = newVec(0.5, 0.5, 0.5)
local selfPos = newVec(coordinate.getAbsoluteCoordinates())
local getRAYGenPos = function()
    local face_offset = newVec(faces["up"]):scale(properties.offset)  
    local wPos = newVec(ship.getWorldspacePosition())
    local yardPos = newVec(ship.getShipyardPosition())
    local offset = yardPos:sub(selfPos):sub(block_offset):sub(face_offset)
    offset = quat.vecRot(ship.getQuaternion(), offset)
    return wPos:sub(offset)
end

local getUpDirection = function()
    local up_vec = newVec(0, 1, 0)
    return quat.vecRot(ship.getQuaternion(), up_vec)
end

local launchRAYEffect = function()
    local up_dir = getUpDirection():norm()
    local spawn_pos = getRAYGenPos()
    local direction = up_dir:copy():norm()
    local length = properties.length
    local particleDensity = 5
    local totalParticles = math.floor(length * particleDensity)
    local motion_vec = direction:copy():scale(3)
    local motion_nbt = string.format("Motion:[%.4f,%.4f,%.4f]", motion_vec.x, motion_vec.y, motion_vec.z)
    for i = 0, totalParticles do
        local progress = i / totalParticles
        local posX = spawn_pos.x + direction.x * progress * length
        local posY = spawn_pos.y + direction.y * progress * length
        local posZ = spawn_pos.z + direction.z * progress * length
        -- 云粒子
        commands.execAsync(string.format(
            "/particle minecraft:cloud %.2f %.2f %.2f 0.2 0.2 0.2 0 2 force",
            posX, posY, posZ
        ))
        -- 光束粒子
        if i % 10 == 0 then
            commands.execAsync(string.format(
                "/particle minecraft:end_rod %.2f %.2f %.2f %.2f %.2f %.2f 0.1 1 force",
                posX, posY, posZ,
                direction.x * 0.05,
                direction.y * 0.05,
                direction.z * 0.05
            ))
        end
        -- 召唤弹丸
        if i % 15 == 0 and i ~= totalParticles then
            local summon_cmd = string.format(
                "/summon createbigcannons:ap_autocannon %.2f %.2f %.2f {ProjectileMass:5000,Damage:1000,%s}",
                posX, posY, posZ, motion_nbt
            )
            commands.execAsync(summon_cmd)
        end
    end
end

local redstoneControl = function()
    while true do
        if redstone.getInput(properties.INPUT) == true then
            launchRAYEffect()
        end
        sleep(0.05)
    end
end
---------------- UI 界面 -----------------
local termUtil = {
    cpX = 1,
    cpY = 1,
}

local absTextField = {
    x = 1,
    y = 1,
    len = 15,
    text = "",
    textCorlor = "0",
    backgroundColor = "8",
}

local genStr = function(s, count)
    local result = ""
    for i = 1, count, 1 do
        result = result .. s
    end
    return result
end

function absTextField:paint()
    local str = ""
    for i = 1, self.len, 1 do
        local text = tostring(self.key[self.value])
        local tmp = string.sub(text, i, i)
        if #tmp > 0 then
            str = str .. tmp
        else
            local tmp2 = ""
            for j = 0, self.len - i, 1 do
                tmp2 = tmp2 .. " "
            end
            str = str .. tmp2
            break
        end
    end

    term.setCursorPos(self.x, self.y)
    term.blit(str, genStr(self.textCorlor, #str), genStr(self.backgroundColor, #str))
end

function absTextField:inputChar(char)
    local xPos, yPos = term.getCursorPos()
    xPos = xPos + 1 - self.x
    local field = tostring(self.key[self.value])
    if #field < self.len then
        if self.type == "number" then
            if char >= '0' and char <= '9' then
                if field == "0" then
                    field = char
                else
                    field = string.sub(field, 1, xPos) .. char .. string.sub(field, xPos, #field)
                end

                self.key[self.value] = tonumber(field)
                termUtil.cpX = termUtil.cpX + 1
            end
            if char == '-' then
                self.key[self.value] = -self.key[self.value]
            end
        elseif self.type == "string" then
            local strEnd = string.sub(field, xPos, #field)
            field = string.sub(field, 1, xPos - 1) .. char .. strEnd
            self.key[self.value] = field
            termUtil.cpX = termUtil.cpX + 1
        end
    end
end

function absTextField:inputKey(key)
    local xPos, yPos = term.getCursorPos()
    local field = tostring(self.key[self.value])
    local minXp = self.x
    local maxXp = minXp + #field
    if key == 259 or key == 261 then 
        if xPos > minXp then
            termUtil.cpX = termUtil.cpX - 1
            if #field > 0 and termUtil.cpX > 1 then
                local index = termUtil.cpX - self.x
                field = string.sub(field, 1, index) .. string.sub(field, index + 2, #field)
            end
            if self.type == "number" then
                local number = tonumber(field)
                if not number then
                    self.key[self.value] = 0
                else
                    self.key[self.value] = number
                end
            elseif self.type == "string" then
                self.key[self.value] = field
            end
        end
    elseif key == 257 or key == 335 then
    elseif key == 262 or key == 263 then
        if key == 262 then
            termUtil.cpX = termUtil.cpX + 1
        elseif key == 263 then
            termUtil.cpX = termUtil.cpX - 1
        end
    elseif key == 264 or key == 258 then
    elseif key == 265 then
    end
    termUtil.cpX = termUtil.cpX > maxXp and maxXp or termUtil.cpX
    termUtil.cpX = termUtil.cpX < minXp and minXp or termUtil.cpX
end

function absTextField:click(x, y)
    local xPos = self.x
    if x >= xPos then
        if x < xPos + #tostring(self.key[self.value]) then
            termUtil.cpX, termUtil.cpY = x, y
        else
            termUtil.cpX, termUtil.cpY = xPos + #tostring(self.key[self.value]), y
        end
    end
end

local newTextField = function(key, value, x, y)
    return setmetatable({ key = key, value = value, type = type(key[value]), x = x, y = y },
        { __index = absTextField })
end

local absSelectBox = {
    x = 1,
    y = 1,
    label = "",
    contents = {},
    count = 0,
    interval = 0,
    fontColor = "8",
    backgroundColor = "f",
    selectColor = "e"
}

function absSelectBox:paint()
    term.setCursorPos(self.x, self.y)
    local select = tostring(self.key[self.value])
    for i = 1, #self.contents, 1 do
        local str = tostring(self.contents[i])
        if select == str then
            term.blit(str, genStr(self.backgroundColor, #str), genStr(self.selectColor, #str))
        else
            term.blit(str, genStr(self.fontColor, #str), genStr(self.backgroundColor, #str))
        end
        for j = 1, self.interval, 1 do
            term.write(" ")
        end
    end
end

function absSelectBox:click(x, y)
    local xPos = x - self.x + 1
    local index = 0
    
    for i = 1, #self.contents do
        local item = tostring(self.contents[i])
        if xPos >= index and xPos <= index + #item then
            self.key[self.value] = self.contents[i]
            termUtil.cpX, termUtil.cpY = self.x, self.y
            term.setCursorPos(termUtil.cpX, termUtil.cpY)
            term.setCursorBlink(false)  
            break
        end
        index = index + #item + self.interval
    end
end

local newSelectBox = function(key, value, interval, x, y, ...)
    return setmetatable(
        { key = key, value = value, interval = interval, x = x, y = y, type = type(key[value]), contents = { ... } },
        { __index = absSelectBox })
end

local runTerm = function()
        local fieldTb = {
            length = newTextField(properties, "length", 20, 1),
            offset = newTextField(properties, "offset", 20, 2),
        }

        local selectBoxTb = {
            INPUT = newSelectBox(properties, "INPUT", 2, 8, 3, "top", "left", "right", "front", "back","bottom"),
        }

        local alarm_flag = false
        term.clear()
        term.setCursorPos(15, 8)
        term.write("Press any key to continue")
        while true do
            local eventData = { os.pullEvent() }
            local event = eventData[1]
            if event == "mouse_up" or event == "key_up" or event == "alarm"
                or event == "mouse_click" or event == "mouse_drag" or event == "key" or event == "char" then
                if not alarm_flag then
                    alarm_flag = true
                else
                    term.clear()
                    term.setCursorPos(1, 1)
                    term.write("length: ")
                    term.setCursorPos(1, 2)
                    term.write("offset: ")
                    term.setCursorPos(2, 3)
                    term.write("Input:")
                    for k, v in pairs(fieldTb) do
                        v:paint()
                    end

                    for k, v in pairs(selectBoxTb) do
                        v:paint()
                    end

                    term.setCursorPos(termUtil.cpX, termUtil.cpY)

                    if event == "mouse_click" then
                        local x, y = eventData[3], eventData[4]
                        local clickedOnField = false
                        for k, v in pairs(fieldTb) do
                            if y == v.y and x >= v.x and x <= v.x + v.len then
                                v:click(x, y)
                                clickedOnField = true
                                break
                            end
                        end
                        if not clickedOnField then
                            for k, v in pairs(selectBoxTb) do
                                if y == v.y then
                                    v:click(x, y)
                                end
                            end
                        end

                    end
                    if event == "mouse_click" then
                        term.setCursorBlink(true)
                        local x, y = eventData[3], eventData[4]
                        local clickedOnField = false
                        for k, v in pairs(fieldTb) do
                            if y == v.y and x >= v.x and x <= v.x + v.len then
                                v:click(x, y)
                                clickedOnField = true
                                break
                            end
                        end
                        if not clickedOnField then
                            for k, v in pairs(selectBoxTb) do
                                if y == v.y then
                                    v:click(x, y)
                                end
                            end
                        end
                    elseif event == "key" then
                        local key = eventData[2]
                        for k, v in pairs(fieldTb) do
                            if termUtil.cpY == v.y and termUtil.cpX >= v.x and termUtil.cpX <= v.x + v.len then
                                v:inputKey(key)
                            end
                        end
                    elseif event == "char" then
                        local char = eventData[2]
                        for k, v in pairs(fieldTb) do
                            if termUtil.cpY == v.y and termUtil.cpX >= v.x and termUtil.cpX <= v.x + v.len then
                                v:inputChar(char)
                            end
                        end
                    end
                    system.updatePersistentData()
                end
            end
        end
end
parallel.waitForAll(redstoneControl, runTerm)
